#pragma once

#include <iostream>
#include <string>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

const int blacklisten = 10;

enum
{
    Sockerr = 2,
    Binderr,
    Listenerr,
    Accepterr
};

class Sock
{
public:
    Sock(){}

    void Socket()
    {
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_listensockfd < 0)
        {
            lg(Fatal, "socker error, %s: %d", strerror(errno), errno);
            exit(Sockerr);
        }
        int opt = 1;
        setsockopt(_listensockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }

    void Bind(uint16_t port)
    {
        sockaddr_in local;
        memset(&local, 0 ,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        int n = bind(_listensockfd,(sockaddr*)&local,sizeof(local));
        if(n < 0)
        {
            lg(Fatal, "bind error, %s: %d", strerror(errno), errno);
            exit(Binderr);
        }
    }

    void Listen()
    {
        int n = listen(_listensockfd, blacklisten);
        if(n < 0)
        {
            lg(Fatal, "listen error, %s: %d", strerror(errno), errno);
            exit(Listenerr);
        }
    }

    //accept连接完需要把ip和port返回去
    int Accept(std::string& ip, uint16_t &port)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int newfd = accept(_listensockfd, (sockaddr*)&client, &len);
        if(newfd < 0)
        {
            lg(Warning, "accept error, %s: %d", strerror(errno), errno);
            return -1;
        }

        //接收完后需要网络转主机
        char ipstr[64];
        inet_ntop(AF_INET, &client.sin_addr, ipstr, sizeof(ipstr));//将addr转到ipstr
        ip = ipstr;
        port = ntohs(client.sin_port);
        return newfd;
    }

    //需要连接谁，把ip和port传过来
    bool Connect(const std::string &ip, const uint16_t& port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &peer.sin_addr);

        int n = connect(_listensockfd, (sockaddr*)&peer, sizeof(peer));
        if(n < 0)
        {
            std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
            return false;
        }
        return true;
    }

  
    void Cloes()
    {
        close(_listensockfd);
    }

    int Sockfd()
    {
        return _listensockfd;
    }
private:
    int _listensockfd = 0;
};